package com.laowang.common.utils.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @Auther laowang
 * @Date 2022/6/18
 * @Description
 */
public class HttpUtilsMy {

    public static CloseableHttpClient httpClient = null;

    static {
        // 连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //    设置最大连接数
        cm.setMaxTotal(200);
        //    设置每个主机的并发数
        cm.setDefaultMaxPerRoute(20);
        /*BasicCookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
        cookie.setDomain(".github.com");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);*/
        httpClient = HttpClients.custom().setConnectionManager(cm)
            //.setDefaultCookieStore(cookieStore)
            .build();
    }

    /**
     *  根据请求地址下载页面数据
     * @param url
     * @return
     */
    public static String doGetHtml(String url){
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(getConfig());
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            // 判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                if (response.getEntity() != null){
                    // 解析数据
                    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                    //System.out.println(content.length());
                    //System.out.println("content:"+ content);

                    return content;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //释放连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //不能关闭HttpClient
                //httpClient.close();
            }
        }
        return "";
    }


    public String doGetImage(String url){
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(getConfig());
        CloseableHttpResponse response = null;
        try {

            response = httpClient.execute(httpGet);
            // 判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                if (response.getEntity() != null){
                    String extName = url.substring(url.lastIndexOf("."));
                    String picName = UUID.randomUUID().toString()+extName;

                    OutputStream outputStream =new FileOutputStream(new File("J:\\img\\"+picName));
                    response.getEntity().writeTo(outputStream);
                    return picName;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //释放连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //不能关闭HttpClient
                //httpClient.close();
            }
        }
        return null;
    }


    public static RequestConfig getConfig(){
        // 配置信息
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)
            .setConnectionRequestTimeout(10*1000)
            .setSocketTimeout(10 * 1000) // 传输数据的时间
            .build();

        return config;
    }

    public static void main(String[] args) {
        //String html = HttpUtilsMy.doGetHtml("https://www.zhcw.com/czfw/sjfx/kl8/"); // 1
        //String html = HttpUtilsMy.doGetHtml("https://www.zhcw.com/czfw/sjfx/kl8/index_2.shtml"); //2
        //String html = HttpUtilsMy.doGetHtml("https://www.zhcw.com/czfw/sjfx/dlt/");
        //System.out.println("解析的数据:\n"+html);
        // https://www.zhcw.com/czfw/sjfx/ssq/  双色球
        // https://www.zhcw.com/czfw/sjfx/dlt/  大乐透
        // https://www.zhcw.com/czfw/sjfx/3d/   3d
        // https://www.zhcw.com/czfw/sjfx/pl3/  排列三
        // https://www.zhcw.com/czfw/sjfx/pl5/  排列五
        // https://www.zhcw.com/czfw/sjfx/qlc/  七乐彩
        // https://www.zhcw.com/czfw/sjfx/qxc/  7星彩
        // https://www.zhcw.com/czfw/sjfx/kl8/  快乐8

        // 资讯详情
        /*String html = HttpUtilsMy.doGetHtml("https://www.zhcw.com/c/2022-06-19/782045.shtml");
        Document document = Jsoup.parse(html);
        Elements select = document.select(".jj-xq-l");
        System.out.println(select);
        for (Element element : select) {
            System.out.println("=====1");
            String h1 = element.select(".jj-xq-t >h1").text();

            System.out.println(h1);
            Elements spans = element.select(".jj-qx-xx > span");// 来源：中彩网
            String first =spans.eq(0).text();
            String second =spans.eq(1).text();
            System.out.println("first:"+first);
            System.out.println("second:"+second);

            Elements ps = element.select(".zwqk > .ztX3w-C  > .jj-xq-zw >p");
            //System.out.println("ps:"+ps);
            for (Element p : ps) {
                System.out.println("得到P标签:"+p.toString());
            }
            System.out.println("=====2");

        }*/

         // 资讯列表页
        String html = HttpUtilsMy.doGetHtml("https://www.zhcw.com/czfw/sjfx/dlt/");
        Document document = Jsoup.parse(html);
        Elements eles = document.select(".jjxw-n > a");
        System.out.println(eles);
        for (Element ele : eles) {

            String str = ele.select(".N-ly >.blue").text();

            if (str.equals("中彩网")){
                System.out.println("===========1");
                String href = ele.attr("href");
                String s = StringUtils.substringAfterLast(href, "/");
                s = StringUtils.substringBefore(s, ".");
                System.out.println("id:"+s);
                href ="https://www.zhcw.com" + href;
                System.out.println(href);
                System.out.println(str);
                String dateStr = ele.select(".N-ly >.ly-sj").text();
                System.out.println(dateStr);
                String img = ele.select(".img>img").attr("src");
                //https://www.zhcw.com/upload/resources/image/2022/06/21/146872_260x195_420x235c.jpg
                img = "https://www.zhcw.com"+img;
                System.out.println(img);
                String strong = ele.select(".N-nr > .N-t >strong").text();
                System.out.println(strong);
                String preNumber = ele.select(".N-nr > .N-zw").text();
                System.out.println(preNumber);
                System.out.println("=========2");

            }
        }




        /*Elements eles = document.select(".jjxw >.jjxw-n > a");
        //System.out.println("解析的数据:\n"+eles);
        for (Element ele : eles) {
            String img = ele.select(".img>img").attr("src");
            //https://www.zhcw.com/upload/resources/image/2022/06/21/146872_260x195_420x235c.jpg
            img = "https://www.zhcw.com"+img;
            System.out.println(img);
            String text = ele.select(".N-nr>.N-t>strong").text();
            System.out.println(text);
            String text1 = ele.select(".N-nr>.N-zw").text();
            System.out.println(text1);
        }*/

    }
}
